<?php
namespace app\common\model;

use Lvht\GeoHash;
use think\Db;

class SiteModel extends BaseModel
{

    protected $name = 'site'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    //类型自动转换
    protected $type = [];

    //添加店铺信息
    public function addData($data)
    {
        if(empty($data['account'])){
            $this->error = '请输入要申请店铺得账号！';
            return false;
        }
        $userModel = new UserModel();
        $field = $userModel->checkUserName($data['account']);
        if(empty($field)){
            $this->error = '用户账号格式错误！';
            return false;
        }
        $uid = $userModel->where($field,$data['account'])->value('uid');
        if(empty($uid)){
            $this->error = '该账户不存在！';
            return false;
        }
        if (!empty($data['coordinate'])){
            $area=explode(',',$data['coordinate']);
            $data['lng']=$area[0];
            $data['lat']=$area[1];
            $data['geohash']=GeoHash::encode($area[0],$area[1]);
        }
        if ($data['dist_id'] > 0) {
            $data['area_name'] = Db::table('area')->where('id', $data['dist_id'])->value('path');
        }elseif($data['city_id'] > 0){
            $data['area_name'] = Db::table('area')->where('id', $data['city_id'])->value('path');
        }elseif($data['prov_id'] > 0){
            $data['area_name'] = Db::table('area')->where('id', $data['prov_id'])->value('path');
        }else{
            unset($data['area_name']);
        }
        if($this->isUpdate(false)->allowField(true)->save($data)){
            $userData=['uid'=>$uid,'site_id'=>$this->getData('site_id'),'group_id'=>'2001'];
            $userModel->isUpdate(true)->save($userData); //反写user管理店铺
            return true;
        }else{
            return false;
        }
    }

    //修改店铺信息
    public function editData($data)
    {
        if (!empty($data['coordinate'])){
            $area=explode(',',$data['coordinate']);
            $data['lng']=$area[0];
            $data['lat']=$area[1];
            $data['geohash']=GeoHash::encode($area[0],$area[1]);
        }
        if ($data['dist_id'] > 0) {
            $data['area_name'] = Db::table('area')->where('id', $data['dist_id'])->value('path');
        }elseif($data['city_id'] > 0){
            $data['area_name'] = Db::table('area')->where('id', $data['city_id'])->value('path');
        }elseif($data['prov_id'] > 0){
            $data['area_name'] = Db::table('area')->where('id', $data['prov_id'])->value('path');
        }else{
            unset($data['area_name']);
        }
        $this->isUpdate(true)->allowField(true)->save($data);
        return true;
    }

    /*读取器*/

    /*修改器*/

}